package com.pro.config;

import com.pro.model.LoginUser;
import com.pro.utils.JwtUtil;
import com.pro.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author ：刘弘禹
 * @description：TODO
 * @date ：2021/12/27 10:57
 * 认证过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    //这里不要实现filter接口，尽量去继承OncePerRequestFilter类，
    // 默认的过滤器接口回存在一些问题导致请求过来过滤器回调用多次

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //TODO 判断返回值是否为null、""、" "，是返回false 反之为true
        if(!StringUtils.hasText(token)){
            //TODO 如果没有token就直接放行，无需去继续解析token，由于没有token就没有认证信息会由后续
            // 过滤器去抛出异常阻止该请求获取资源
            filterChain.doFilter(request,response);
            //阻止后续代码执行
            return;
        }
        //解析token
        String subject;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            //获取token中的值
            subject = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String key = "loginUserId:"+subject;
        LoginUser loginUser = redisCache.getCacheObject(key);
        //如果redis没有就抛出异常
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        //TODO UsernamePasswordAuthenticationToken对象必须使用三个参数传值，三个参数的构造器在内部会将是否认证的成员变量设置为true
        // 第一个参数为用户的信息，null，第三个参数为用户的权限信息，权限信息也被封装到了LoginUser对象中可以直接获取
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行进入下一个过滤器
        filterChain.doFilter(request,response);
    }
}